package com.qyhl.module_practice.order;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.hawk.Hawk;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeListBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeOrderListBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeOrderOptionBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.ninephotolayout.BGASortableNinePhotoLayout;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.weavey.loading.lib.LoadingLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PRACTICE_ORDER)
public class PracticeOrderActivity extends BaseActivity implements PracticeOrderContract.PracticeOrderView, BGASortableNinePhotoLayout.Delegate {
    @BindView(R2.id.type)
    TextView type;
    @BindView(R2.id.matter)
    TextView matter;
    @BindView(R2.id.area)
    TextView area;
    @BindView(R2.id.address)
    EditText address;
    @BindView(R2.id.phone)
    EditText phone;
    @BindView(R2.id.content)
    EditText content;
    @BindView(R2.id.name)
    EditText name;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.back_btn)
    ImageView backBtn;
    @BindView(R2.id.NinePhotoLayout)
    BGASortableNinePhotoLayout NinePhotoLayout;
    @BindView(R2.id.title)
    TextView title;

    /**
     * 上传token
     */
    private UpTokenBean mUpToken;
    /**
     * 图片多选
     */
    public static final int CHOOSE_REQUEST = 200;

    public static final int TYPE_REQUEST = 202;


    /**
     * 图片数据
     */
    private List<LocalMedia> selectedList = new ArrayList<>();

    private PracticeOrderPresenter mPresenter;

    private LoadingDialog.Builder builder;

    private PracticeOrderListBean mData;

    private String volId;

    private String userName;

    private String instId;

    private String upContent, upAddress, upName, upType, upStreetId, upPhone;

    private String titleName;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_order;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.fitsSystemWindows(true).statusBarColor(R.color.global_base).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        volId = getIntent().getStringExtra("id");
        userName = getIntent().getStringExtra("userName");
        instId = getIntent().getStringExtra("instId");
        titleName = getIntent().getStringExtra("title");
        mPresenter = new PracticeOrderPresenter(this);
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getTypeList(instId);
    }

    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        builder = new LoadingDialog.Builder(PracticeOrderActivity.this);
        builder.setTitle("提交中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

        if (StringUtils.isEmpty(titleName)) {
            title.setText("群众点单");
        } else {
            title.setText(titleName);
        }

        //九宫格设置监听
        NinePhotoLayout.setDelegate(this);

    }

    private void setListeners() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getTypeList(instId);
            }
        });
    }

    private void checkData() {
        builder.show();

        if (!CommonUtils.getInstance().getUserCheck().equals("1") && CommonUtils.getInstance().getSite() == 217) {
            showToast("用户信息审核中，暂时无法使用该功能！", INFO);
            return;
        }

        upType = type.getText().toString();
        if (StringUtils.isEmpty(upType)) {
            showToast("请选择类别！", 4);
            builder.dismiss();
            return;
        }

        if (StringUtils.isEmpty(matter.getText().toString())) {
            showToast("请选择机构！", 4);
            builder.dismiss();
            return;
        }


        upAddress = address.getText().toString();
        if (StringUtils.isEmpty(upAddress)) {
            showToast("请填写地址！", 4);
            builder.dismiss();
            return;
        }

        upContent = content.getText().toString();
        if (StringUtils.isEmpty(upContent)) {
            showToast("请填写内容！", 4);
            builder.dismiss();
            return;
        }

        upName = name.getText().toString();
        if (StringUtils.isEmpty(upName)) {
            showToast("请填写姓名！", 4);
            builder.dismiss();
            return;
        }

        upPhone = phone.getText().toString();
        if (StringUtils.isEmpty(upPhone)) {
            showToast("请填写联系方式！", 4);
            builder.dismiss();
            return;
        }

        if (selectedList != null && selectedList.size() > 0) {
            if (mUpToken == null) {
                mPresenter.getToken(true);
                return;
            }
            List<UploadBean> uploadBeans = new ArrayList<UploadBean>();
            for (int i = 0; i < selectedList.size(); i++) {
                LocalMedia image = selectedList.get(i);
                UploadBean videoCoverBean = new UploadBean();
                videoCoverBean.setType(2);
                videoCoverBean.setPath(image.getCompressPath());
                videoCoverBean.setPostion(0);
                uploadBeans.add(videoCoverBean);
            }
            QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getUptoken(), mUpToken.getPrefix(), new UploadResultListener() {
                @Override
                public void uplaodError() {
                    builder.dismiss();
                    showToast("上传图片出错", INFO);
                }

                @Override
                public void uploadSuccess(List<UploadBean> files) {
                    Log.i("practice_act_apply", "uploadSuccess");
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < files.size(); i++) {
                        if (i == files.size() - 1) {
                            stringBuilder.append(files.get(i).getUrl());
                        } else {
                            stringBuilder.append(files.get(i).getUrl()).append(",");
                        }
                    }

                    mPresenter.upload(volId, upStreetId, upAddress, upContent, upName, userName, upType, stringBuilder.toString(), upPhone);

                }

                @Override
                public void uploadPre(double percent) {

                }
            });
        } else {
            mPresenter.upload(volId, upStreetId, upAddress, upContent, upName, userName, upType, "", upPhone);
        }


    }


    @OnClick({R2.id.upload_btn, R2.id.back_btn, R2.id.type, R2.id.matter, R2.id.area, R2.id.cancel_btn})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.upload_btn) {
            checkData();
        } else if (id == R.id.cancel_btn) {
            finish();
        } else if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.type) {
            if (mData != null && mData.getTypes() != null && mData.getTypes().size() > 0) {
                Bundle bundle = new Bundle();
                bundle.putInt("type", 0);
                bundle.putSerializable("list", (Serializable) mData.getTypes());
                RouterManager.router(this, ARouterPathConstant.PRACTICE_ORDER_TYPE, bundle, TYPE_REQUEST);
            } else {
                showToast("暂无任何类别！", 4);
            }
        } else if (id == R.id.matter) {
            if (mData != null && mData.getStreetList() != null && mData.getStreetList().size() > 0) {
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                Hawk.put("orderStreetList", mData.getStreetList());
                RouterManager.router(this, ARouterPathConstant.PRACTICE_ORDER_TYPE, bundle, TYPE_REQUEST);
            } else {
                showToast("暂无任何机构！", 4);
            }
        } else if (id == R.id.area) {
        }
    }

    @Override
    public void setTypeList(PracticeOrderListBean bean) {
        backBtn.setVisibility(View.GONE);
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        mData = bean;
    }

    @Override
    public void setTypeError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        backBtn.setVisibility(View.VISIBLE);
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @Override
    public void uploadSuccess(String msg) {
        builder.dismiss();
        showToast(msg, 4);
        finish();
    }

    @Override
    public void uploadError(String msg) {
        builder.dismiss();
        showToast(msg, 4);
    }

    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUpload) {
        mUpToken = data;
        if (isUpload) {
            checkData();
        }
    }

    @Override
    public void getTokenError(boolean isUpload) {
        if (isUpload) {
            builder.dismiss();
            showToast("上传失败！", 4);
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        PictureSelector.create(PracticeOrderActivity.this)
                //仅图片
                .openGallery(PictureMimeType.ofImage())
                //每行显示4张
                .imageSpanCount(4)
                .maxSelectNum(9)
                .selectionMode(PictureConfig.MULTIPLE)
                //允许使用相机
                .isCamera(true)
                //允许预览图片
                .previewImage(true)
                .isZoomAnim(true)
                .compress(true)
                .selectionMedia(selectedList)
                // 小于100kb的图片不压缩
                .minimumCompressSize(100)
                .forResult(CHOOSE_REQUEST);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        for (int i = 0; i < selectedList.size(); i++) {
            if (selectedList.get(i).getCompressPath().equals(NinePhotoLayout.getData().get(position))) {
                selectedList.remove(i);
            }
        }

        NinePhotoLayout.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        MNImageBrowser.showImageBrowser(this, view, position, models);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> resultList;
        switch (requestCode) {
            case CHOOSE_REQUEST:
                resultList = PictureSelector.obtainMultipleResult(data);
                if (resultList != null && resultList.size() > 0) {
                    selectedList.clear();
                    selectedList.addAll(resultList);
                }
                ArrayList<String> select = new ArrayList<>();

                for (int i = 0; i < selectedList.size(); i++) {
                    select.add(selectedList.get(i).getCompressPath());
                }

                NinePhotoLayout.setData(select);
                break;
            case TYPE_REQUEST:
                if (data != null && data.getExtras() != null) {
                    int mType = data.getExtras().getInt("type", 0);
                    if (mType == 0) {
                        List<PracticeOrderOptionBean> optionList = (List<PracticeOrderOptionBean>) data.getExtras().getSerializable("list");
                        mData.setTypes(optionList);
                        if (optionList != null && optionList.size() > 0) {
                            boolean tag = false;
                            for (int i = 0; i < optionList.size(); i++) {
                                if (optionList.get(i).isChecked()) {
                                    tag = true;
                                    type.setText(optionList.get(i).getName());
                                }
                            }

                            if (!tag) {
                                type.setText("");
                            }
                        }
                    } else {
                        List<PracticeListBean> streetList = Hawk.get("orderStreetList");

                        if (streetList != null && streetList.size() > 0) {
                            mData.setStreetList(streetList);
                            boolean tag = false;
                            for (int i = 0; i < streetList.size(); i++) {
                                if (streetList.get(i).isChecked()) {
                                    tag = true;
                                    matter.setText(streetList.get(i).getName());
                                    upStreetId = streetList.get(i).getId() + "";
                                }
                            }

                            if (!tag) {
                                matter.setText("");
                                upStreetId = "";
                            }
                        }
                    }
                }
                break;
            default:
                break;
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_ORDER);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_ORDER);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Hawk.delete("orderStreetList");
    }
}
